package com.bizmda.bizsip.source.api;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * Source层获取App调用接口
 * @param <T> App服务的接口类
 */
public class SourceClientFactory<T> {
    private static final Map<String,Object> appServiceClientCache = new HashMap<>();
    private static final Map<String,Class> classCache = new HashMap<>();
    /**
     * 获取App服务调用接口
     * @param tClass App服务的接口类（要求是interface）
     * @param appServiceId 应用服务ID
     * @param <T> 接口类泛型
     * @return 接口调用句柄
     */
    public static <T> T getAppServiceClient(Class<T> tClass, String appServiceId) {
        Class clazz = classCache.get(appServiceId);
        if (clazz != null) {
            if (tClass == clazz) {
                Object obj = appServiceClientCache.get(appServiceId);
                return (T) obj;
            }
        }
        final AppServiceClientProxy<T> appServiceClientProxy = new AppServiceClientProxy<>(tClass,appServiceId);
        Object obj = Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, appServiceClientProxy);
        appServiceClientCache.put(appServiceId,obj);
        classCache.put(appServiceId,tClass);
        return (T) obj;
    }
}
